<?php
namespace app\api\controller;


use app\common\model\UserModel;
use app\common\module\Wechat;
use think\Db;

class Index extends Common
{
    public function index(){
        echo "网站正在开发中...";
//        phpinfo();
    }
    public function login(){
        $data = $this->checkSign(false);
        $code = $data['code']??"";
        $headlike = $data['headlike']??"";
        $nickname = $data['nickname']??"";
        $gender = $data['gender']??"";
        $share_user = intval($data['share_user']??"");
        if(!$code){
            return package(20006,'code错误');
        }
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".config('public.wx_appid')."&secret=".config('public.wx_secret')."&js_code=".$code."&grant_type=authorization_code";
        $res =  curl_get($url);
        if(isset($res['errcode'])){
            return package($res['errcode'],$res['errmsg']);
        }
        $openid = $res['openid'];
        if(!$openid){
            return package(10068,'未获取到openid');
        }

        $result = Db::name('users')->where("openid",$openid)->field('user_class,is_lock,integral,money,id as user_id,region_id,public_openid,unionid,parent_id')->find();
        $updatedata = [
            "headimgurl"=>$headlike,
            'gender'=>$gender,
            'nickname'=>$nickname,
            'unionid'=>$res['unionid']??"",
            'is_out'=>0,
            'login_ip'=>get_client_ip(),
            'login_time'=>date("Y-m-d H:i:s")
        ];
        Db::startTrans();
        $returnData = $updatedata;
        if($result){
            if($result['is_lock'] ==1){
                Db::rollback();
                return package(1002,'当前账号已锁定！请联系客服');
            }
            if(!$result['public_openid'] && isset($res['unionid'])){ //如果没有就获取openid
                $followInfo = Db::name('follow')->where('unionid',$res['unionid'])->field('openid,qr_scene_str')->find();
                if(isset($followInfo["openid"]) && $followInfo["openid"]){
                    $updatedata['public_openid'] = $followInfo["openid"];
                }
                if(isset($followInfo["qr_scene_str"]) &&  $followInfo["qr_scene_str"] && $followInfo["qr_scene_str"] !=$result["user_id"] && !$result["parent_id"]){
                    $updatedata['parent_id'] = $followInfo["qr_scene_str"];
                }
            }
            if(!isset($updatedata['parent_id']) && $share_user  && !$result["parent_id"]){
                $updatedata['parent_id'] = $share_user;
            }

            $rs = UserModel::where('id',$result['user_id'])->update($updatedata);
            $returnData['is_first']  = false;
            $returnData['is_lock']  = $result['is_lock'];
            $returnData = array_merge($returnData,$result);
        }else{
            $followInfo = Db::name('follow')->where('unionid',$res['unionid'])->field('openid,qr_scene_str')->find();
            if(isset($followInfo["openid"]) && $followInfo["openid"]){
                $updatedata['public_openid'] = $followInfo["openid"];
            }
            if(isset($followInfo["qr_scene_str"]) && $followInfo["qr_scene_str"]){
                $updatedata['parent_id'] = $followInfo["qr_scene_str"];
            }
            if(!isset($updatedata['parent_id']) && $share_user){
                $updatedata['parent_id'] = $share_user;
            }
            $inserData = array_merge($updatedata,[
                'openid'=>$openid,
                'create_time'=>date("Y-m-d H:i:s"),
                'integral'=>0,
                'money'=>0,
            ]);
            $rs = Db::name('users')->insertGetId($inserData);
            $returnData['is_first']  = true;
            $returnData['user_class']  = 1;
            $returnData['integral']  = 0;
            $returnData['money']  = 0;
            $returnData['user_id']  = $rs;
            $returnData['region_id']  = null;
            $returnData['is_lock']  = 0;
        }
        $che =  redisHashGet('auth',$openid);
        if($che){ //如果之前有。先清空
            redisHashDel('auth',$che['token']);
            redisHashDel('auth',$openid);
        }
        $token = getRandStr(32);
        $returnData['token']  = $token;
        redisHashSet('auth',$token,array_merge($returnData,['session_key'=>$res['session_key'],'openid'=>$openid]));
        redisHashSet('auth',$openid,array_merge($returnData,['session_key'=>$res['session_key'],'openid'=>$openid]));
        if($rs){
            Db::commit();
            return package(0,'登录成功',$returnData);
        }else{
            Db::rollback();
            return package(10005,'登录失败');
        }
    }
    public function getUserClass(){
        $data  = $this->checkSign();
        $class = Db::name('users')->where('id',$data['user_id'])->field('user_class,region_id,integral,money')->find();
        //取出来更新
        $token = $data['token']??'';
        $userInfo = redisHashGet('auth',$token);
        $userInfo['user_class'] = $class['user_class'];
        $userInfo['region_id'] = $class['region_id'];
        $userInfo['integral'] = $class['integral'];
        $class['money'] = floatval($class['money']);
        $userInfo['money'] =$class['money'];
        redisHashSet('auth',$token,$userInfo);
        redisHashSet('auth',$userInfo['openid'],$userInfo);

        $class['weight'] = Db::name('order_detail')->where('user_id',$data['user_id'])->sum('number');
        return package(0,'success',$class);
    }
    public function getPhone(){
        $data = $this->checkSign();
        include_once VENDORURLS."/wx/wxBizDataCrypt.php";
        $appid = config('public.wx_appid');
        $sessionKey = isset($data['session_key'])?$data['session_key']:'Z8lUzRr04g7n42AIBYjgbA==';
        $encryptedData=  isset($data['encryptedData'])?$data['encryptedData']:'';
        $iv =  input('post.iv');
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            $data = json_decode($data,true);
            return package(0,'成功',$data['phoneNumber']);
        } else {
            print($errCode . "\n");
        }
    }
    public function getStaff(){
        $this->checkSign(false);
        $phone =  Db::name('config')
            ->where('id',1)
            ->cache(true)
            ->value('phone');
        return package(0,'获取成功',$phone);
    }
    public function layout(){
        $data = $this->checkSign();
        redisHashDel('auth',$data['token']);
        if(isset($data['openid']) && $data['openid'])  redisHashDel('auth',$data['openid']);
        $mtime = config('public.line_time')+1;
        $min5  = date ( "Y-m-d H:i:s" , strtotime ( "-{$mtime} minute" ));
        //退出登录。并设置最后登录时间为 5分钟之前
        Db::name('users')->where('id',$data['user_id'])->update(['is_out'=>1,'location_time'=>$min5]);
        return package(0,'退出成功');
    }
    public function getShareCode(){
        $data = $this->checkSign();
        $we  = new Wechat();
        $acc = $we->getPublicAccess();
        $data = '{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$data['user_id'].'"}}}';; //永久
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$acc;
        $res_data = curl_post($url,$data);
        return package(0,'退出成功',json_decode($res_data));
    }
    public function getRecommend(){
        $data = $this->checkSign();

        $where = [["parent_id","=",$data['user_id']]];
        $start_time =$data['start_time']??"";
        $end_time =$data['end_time']??"";
        if($start_time && $end_time){
            $where[] =  ['create_time','between time',[$start_time.' 00:00:00',$end_time." 23:59:59"]];
        }
        $list = Db::name('users')->where($where)
            ->field("nickname,true_name,user_class,create_time,headimgurl,id as user_id")
            ->order('id','desc')
            ->select();
        $userIsIn = [];
        $sum = "";
        $sum_weight ="";
        foreach ($list as $v){
            $userIsIn[] = $v["user_id"];
            $sum.="sum( user_id = ".$v["user_id"].") as u_".$v["user_id"]."," ."sum( if( user_id = ".$v["user_id"].",total_money,0))  as t_".$v["user_id"]."," ;
            $sum_weight.="sum( if( user_id = ".$v["user_id"].",number,0))  as w_".$v["user_id"]."," ;
        }

        $sum = rtrim ( $sum ,  ",");
        $sum_weight = rtrim ( $sum_weight ,  ",");
        $address = Db::name("users_address")->whereIn("user_id",$userIsIn)->field("true_name,phone,type as address_type,user_id")->select();


        $order_list = Db::name("orders")
            ->whereIn("order_status","2,3")
            ->whereIn("user_id",$userIsIn)
            ->field($sum)->select();
        $weight_list = Db::name("order_detail")
            ->whereIn("user_id",$userIsIn)
            ->field($sum_weight)->select();

        foreach ($list as $k=>$v){
            //地址
            foreach ($address as $val){
                if($v["user_id"] == $val["user_id"]){
                    $list[$k]["true_name"] =$val["true_name"];
                    $list[$k]["phone"] =$val["phone"];
                    $list[$k]["address_type"] =$val["address_type"];
                }
            }

            //重量

            foreach ($weight_list as $v1){
                foreach ($v1 as $kk1=>$vvv1){
                    $ge = explode("_",$kk1);
                    if($ge[1] == $v["user_id"]){
                        if($ge[0] =="w"){
                            $list[$k]["order_weight"] = $vvv1;
                        }
                    }
                }
            }

            //订单
            foreach ($order_list as $vv){
                foreach ($vv as $kk=>$vvv){
                    $ge = explode("_",$kk);
                    if($ge[1] == $v["user_id"]){
                        if($ge[0] =="u"){
                            $list[$k]["order_count"] = $vvv;
                        }
                        if($ge[0] =="t"){
                            $list[$k]["order_money"] = $vvv;
                        }
                    }
                }
            }
        }
        return package(0,'获取成功',$list);
    }
}
